<template>
  <div class="amapBox" :style="{ height }">
    <el-amap
      class="amap-box"
      :vid="'amap-vue'"
      :plugin="plugin"
      :center="mapCenter"
      :events="events"
      ref="map"
    >
      <el-amap-marker
        vid="component-marker"
        :position="markPosition"
        :icon="require('../../assets//_my.png')"
        :draggable="true"
        :raiseOnDrag="true"
        :events="markEvents"
      ></el-amap-marker>
    </el-amap>
  </div>
</template>
<script>
export default {
  name: "AMap",
  //考虑到动态需求，允许默认中心点和地图高度从父组件传递来，如果不传递，则使用默认值
  props: {
    center: {
      type: Array,
      default: () => {
        return [106.61994874, 26.64158513];
      },
    },
    height: {
      type: String,
      default: "100vw",
    },
  },
  data() {
    return {
      mapCenter: [], //地图中心坐标数组，因为可能会从父组件传递，所以初始为空，将会在created生命周期中赋值
      loaded: false,
      /*events是包含地图事件的对象，init是地图初始化时触发，moveeend地图拖动时触发，click点击地图触发，zoomchange地图缩放级别更改后触发*/
      events: {
        init: this.mapInit,
        moveend: this.moveend,
        zoomchange: this.zoomchange,
        click: this.mapClick,
      },
      markEvents: {
        //标记事件
        click: this.markClick, //标记点击触发
        dragend: this.markDragend, //标记拖动触发
      },
      plugin: [
        //插件
        {
          pName: "Geolocation", //定位插件
          events: {
            init: this.getGolocationInit, //定位初始化函数
          },
        },
        "Autocomplete",
        "PlaceSearch",
        "Scale",
        "OverView",
        "PolyEditor",
        "ToolBar",
      ],
      markPosition: [106.61994874, 26.64158513], //标记物位置
      cityInfo: {}, //当前城市信息
    };
  },
  methods: {
    // 地图初始化函数
    mapInit(o) {
      // console.log(o.getCenter())
      // console.log(this.$refs.map.$$getInstance())
      o.getCity((result) => {
        this.cityInfo = result;
      });
    },
    //点图点击事件
    async mapClick(e) {
      // console.log(e)
      //addressComponent
      let { lng, lat } = e.lnglat;
      this.markPosition = [lng, lat];
      let addressInfo = await this.getAddressFromLngLat(lng, lat);
    },
    //定位初始化
    getGolocationInit(o) {
      o.getCurrentPosition((status, result) => {
          console.log(result)
        if (result && result.position) {
           console.log(result)
        //   let { position, addressComponent, formattedAddress } = result;
        //   let { lng, lat } = position;
        //   this.mapCenter = [lng, lat];
        //   this.markPosition = [lng, lat];
        //   this.loaded = true;
        //   this.$nextTick();
         }
      });
    },
    //地图移动
    moveend() {},
    //地图比例改变
    zoomchange() {},
    //点击图标
    markClick() {
       alert('xxx')
    },
    //根据经纬度获取地址
    getAddressFromLngLat(lng, lat) {
      let { cityInfo } = this;
      let { citycode } = cityInfo;
      return new Promise((resolve, reject) => {
        AMap.plugin("AMap.Geocoder", () => {
          let geocoder = new AMap.Geocoder({
            // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
            city: citycode,
          });
          geocoder.getAddress([lng, lat], (status, result) => {
            // console.log(status,result)
            if (status === "complete" && result.info === "OK") {
              // result为对应的地理位置详细信息
              let { addressComponent, formattedAddress } = result.regeocode;
              let { province, city, district, township } = addressComponent;
              resolve({
                formattedAddress,
                province,
                city,
                district,
                township,
              });
            }
          });
        });
      });
    },
    //标记点拖动结束
    async markDragend(e) {
      let { lng, lat } = e.lnglat;
      let addressInfo = await this.getAddressFromLngLat(lng, lat);
     
    },
    //通过地址查询经纬度
    getLngLatFromAddress(address) {
      if (!address) return;
      let { cityInfo } = this;
      let { citycode } = cityInfo;
      return new Promise((resolve, reject) => {
        AMap.plugin("AMap.Geocoder", () => {
          let geocoder = new AMap.Geocoder({
            city: citycode,
          });
          geocoder.getLocation(address, (status, result) => {
            let lngLatArr = [];
            let { geocodes = [] } = result;
            geocodes.forEach((item, index) => {
              let { lng, lat } = item.location;
              lngLatArr.push({ lng, lat });
            });
            resolve(lngLatArr);
          });
        });
      });
    },
    //搜索提示
    getSearchAddresList(keyword) {
      let { cityInfo } = this;
      let { citycode } = cityInfo;
      return new Promise((resolve, reject) => {
        AMap.plugin("AMap.Autocomplete", () => {
          // 实例化Autocomplete
          let autoOptions = {
            //city 限定城市，默认全国
            city: citycode,
          };
          let autoComplete = new AMap.Autocomplete(autoOptions);
          autoComplete.search(keyword, (status, result) => {
            // 搜索成功时，result即是对应的匹配数据
            if (status === "complete" && result.info === "OK") {
              // result为对应的地理位置详细信息
              resolve(result.tips);
            }
          });
        });
      });
    },
  },
  created() {
    this.mapCenter = this.center;
  },
  mounted() {},
};
</script>
<style scoped lang="less">
.amapBox {
  width: 100vw;
}
</style>

